//
//  ManagementController.m
//  QRMaster
//
//  Created by myApple on 16/4/25.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "ManagementController.h"
#import "ManagementCell.h"
#import "CommunityManageController.h"
#import "ManageStaffVC.h"
#import "ManageGuestVC.h"
#import "OpertionPlist.h"
#import "communityModel.h"
#import "CommunitySelectTableViewCell.h"
#import "RequestNetWork.h"
#import "MJRefresh.h"
#import "PromptInfoView.h"
#import "checkPower.h"
#import "QRSingleton.h"
#import "CommunityListInfo.h"
#import "CommunityListModel.h"
#import "NoInfoPromtView.h"
#import "ManagementModel.h"
#import "ManagementData.h"
#import "ManagementMultipleCell.h"

@interface ManagementController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,NoInfoPromtViewDelegate>
{
    UITableView * managementInfoTabelView;
    NSMutableArray * managementInfoArray;
    UIView * backView;
    UITableView * communityListTabelView;
    NSMutableArray * communityListArray;
    QRSingleton * singleton;
    NoInfoPromtView * promtView;
    UIView * NetWorkBreakView;
    ManagementData * manageData;
}

@end

static const float communityCellHeight = 50;

@implementation ManagementController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netWorkBreakFromFile) name:@"netWorkBreak" object:nil];//断网从文件获取数据
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(JoinNetWorkRefresh) name:@"netWorkJion" object:nil];//连网就刷新一下数据
    manageData = [[ManagementData alloc]init];
    singleton = [QRSingleton sharedQRSingleton];
    communityListArray = [[NSMutableArray alloc]init];
    managementInfoArray = [[NSMutableArray alloc]init];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    [self netWorkStatusView];
    [self prepareTableView];
    [self getCommunityData];
    [self NoCommunityView];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     self.navigationItem.title = NSLocalizedString(@"managerMent", nil);
     [self prepareData];
}

#pragma mark ---------- 初始化数据
-(void)roleJudge
{
    if (singleton.roleIndex == 0 || singleton.roleIndex == 4) {
        promtView.hidden = NO;
        return;
    }
    promtView.hidden = YES;
    [self prepareData];
}

-(void)prepareData
{
    managementInfoArray = [manageData getManageArrayWithRole:singleton.roleIndex];
    [managementInfoTabelView reloadData];
}

#pragma mark -----------网络状况
-(void)netWorkStatusView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = ScreenWidth - 40;
    float y = 2;
    float width = 40;
    float height = 40;
    
    //断网时候出现的提示
    x = 0;
    y = 0;
    width = ScreenWidth;
    height = 40;
    NetWorkBreakView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    NetWorkBreakView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:242 /255.0 blue:187 /255.0 alpha:1];
    NetWorkBreakView.hidden = YES;
    [self.view addSubview:NetWorkBreakView];
    
    x = 0;
    y = 10;
    width = ScreenWidth;
    height = 20;
    UILabel * netWorkBreakLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    netWorkBreakLabel.text = NSLocalizedString(@"managerNoNetWork", nil);
    netWorkBreakLabel.textAlignment = NSTextAlignmentCenter;
    netWorkBreakLabel.font = [UIFont systemFontOfSize:14.0];
    [NetWorkBreakView addSubview:netWorkBreakLabel];
}

-(void)prepareTableView
{
    float x = 0;
    float y = 0;
    float height = UI_SCREEN_HEIGHT - 64 - y - 49;
    float width = UI_SCREEN_WIDTH;
    
    managementInfoTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStyleGrouped];
    managementInfoTabelView.backgroundColor = UIColorFromRGB(0xebebeb);
    managementInfoTabelView.delegate = self;
    managementInfoTabelView.dataSource = self;
    managementInfoTabelView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:managementInfoTabelView];
    
    x = 0;
    y = 0;
    width = UI_SCREEN_WIDTH;
    height = UI_SCREEN_HEIGHT;
    backView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    backView.backgroundColor = UIColorFromRGBAndA(0x000000, 0.5);
    backView.hidden = YES;
    backView.userInteractionEnabled = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:backView];
    UITapGestureRecognizer * backViewTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenView)];
    backViewTap.delegate = self;
    [backView addGestureRecognizer:backViewTap];
    
    x = 0;
    y = UI_SCREEN_HEIGHT;
    width = UI_SCREEN_WIDTH;
    height = communityCellHeight * 5;
    communityListTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    communityListTabelView.backgroundColor = [UIColor whiteColor];
    communityListTabelView.delegate = self;
    communityListTabelView.dataSource = self;
    communityListTabelView.tableFooterView = [[UIView alloc]init];
    [backView addSubview:communityListTabelView];
    
    __weak ManagementController * weakSelf = self;
    [communityListTabelView.mj_header beginRefreshing];
    communityListTabelView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf getCommunityData];
    }];
    
}

#pragma mark ---------- 有网络的情况下
-(void)JoinNetWorkRefresh
{
    NetWorkBreakView.hidden = YES;
    managementInfoTabelView.frame = CGRectMake(managementInfoTabelView.frame.origin.x, 0, managementInfoTabelView.frame.size.width, UI_SCREEN_HEIGHT- 49 - 64);
    [self getCommunityData];
}

#pragma mark ---------- 没有网络的情况下
-(void)netWorkBreakFromFile
{
    NetWorkBreakView.hidden = NO;
    managementInfoTabelView.frame = CGRectMake(managementInfoTabelView.frame.origin.x, 40, managementInfoTabelView.frame.size.width, UI_SCREEN_HEIGHT - 40 - 49 - 64);
    [managementInfoTabelView reloadData];
//    NSDictionary * communityInfo = [OpertionPlist readDataFromPlist];
//    communityArray = [communityInfo objectForKey:COMMUNITYINFOFORKEY];
}

#pragma mark ----------- 没有集群的提示view
-(void)NoCommunityView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = self.view.frame.size.height;
    promtView = [[NoInfoPromtView alloc]initWithFrame:CGRectMake(x, y, width, height)];
//    [promtView prepareViewWith:@"ic_锁掌柜_70" withPromt:NSLocalizedString(@"noCommunityNow", nil)];
    [promtView prepareViewWithPromtTitle:NSLocalizedString(@"noCommunityNow", nil)];
    promtView.hidden = YES;
    promtView.delegate = self;
    [self.view addSubview:promtView];
}

#pragma mark ----------- NoInfoPromtViewDelegate
-(void)clickRefresh
{
    [self getCommunityData];
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}


#pragma mark ---------- 点击背景取消
-(void)hiddenView
{
    [self animationWithTabelViewHidden];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == communityListTabelView) {
        return 1;
    }
    return managementInfoArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (communityListTabelView == tableView) {
        return communityListArray.count;
    }
    else
    {
        NSArray * rowArray = managementInfoArray[section];
        return rowArray.count;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == communityListTabelView) {
        return 50.0;
    }
    else
    {
        if (indexPath.section == managementInfoArray.count - 1) {
            return 68.0;
        }
        else
        {
            return 56.0;
        }
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == managementInfoTabelView) {
        static  NSString * cellId = @"cellId";
        ManagementCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[ManagementCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        if (managementInfoArray.count > indexPath.section) {
            NSArray * rowData = managementInfoArray[indexPath.section];
            ManagementModel * model = rowData[indexPath.row];
            if (indexPath.section == managementInfoArray.count - 1) {
                static NSString * newCellId = @"newCellId";
                ManagementMultipleCell * newCell = [tableView dequeueReusableCellWithIdentifier:newCellId];
                if (!newCell) {
                    newCell = [[ManagementMultipleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:newCellId];
                }
                newCell.imageName = model.imageNameString;
                newCell.textTitle = model.titleNameString;
                newCell.communityName  = singleton.communityName;
                return newCell;
            }
            else
            {
                cell.imageName = model.imageNameString;
                cell.textTitle = model.titleNameString;
            }
        }
        return cell;
    }
   else
   {
       static  NSString * communityCellID = @"communityCellId";
       UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:communityCellID];
       if (!cell) {
           cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:communityCellID];
       }
       CommunityListModel * model = [communityListArray objectAtIndex:indexPath.row];
       cell.textLabel.text = model.communityName;
       if ([singleton.communityId isEqualToString:model.communityId]) {
           cell.textLabel.textColor = UIColorFromRGB(0x00aff0);
       }
       else
       {
           cell.textLabel.textColor = UIColorFromRGB(0x333333);
       }
       cell.textLabel.font = [UIFont systemFontOfSize:17.0];
       cell.textLabel.textAlignment = NSTextAlignmentCenter;
       return cell;
   }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (communityListTabelView == tableView) {
        return 0.0;
    }
    return 16.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == communityListTabelView) {
        CommunityListModel * model = communityListArray[indexPath.row];
        singleton.currentAreaCodeString = model.areaCodeString;
        singleton.communityId = model.communityId;
        singleton.communityName = model.communityName;
        singleton.roleIndex = [model.role integerValue];
        [[NSUserDefaults standardUserDefaults] setObject:model.communityId forKey:@"communityId"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self roleJudge];
        [communityListTabelView reloadData];
        [self animationWithTabelViewHidden];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        return;
    }
    if ((indexPath.section == 0) && (singleton.roleIndex == 1 || singleton.roleIndex == 2)) {
        if (indexPath.row == 0) {
            ManageStaffVC * MSVC = [[ManageStaffVC alloc]init];
            MSVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:MSVC animated:YES];
        }
        else
        {
            ManageGuestVC * MGVC = [[ManageGuestVC alloc]init];
            MGVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:MGVC animated:YES];
        }
    }
    else if ((indexPath.section == 0) && (singleton.roleIndex == 3))
    {
        ManageStaffVC * MSVC = [[ManageStaffVC alloc]init];
        MSVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:MSVC animated:YES];
    }
    else if ((indexPath.section == 0) && (singleton.roleIndex == 5))
    {
        ManageGuestVC * MGVC = [[ManageGuestVC alloc]init];
        MGVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:MGVC animated:YES];
    }
   else if (indexPath.section == 1 && singleton.roleIndex == 1)
   {
        if (indexPath.row == 0) {
            CommunityManageController * cmc = [[CommunityManageController alloc]init];
            cmc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:cmc animated:YES];
        }
       else
       {
           [self animationWithTableViewShow];
       }
    }
    else
    {
         [self animationWithTableViewShow];
    }
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)getCommunityData
{
    if ([self IsHaveNetwork]) {
        [communityListTabelView.mj_header endRefreshing];
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
   __weak ManagementController * weakSelf = self;
    power.powerBlock = ^(id data,id error)
    {
        [self stopWaiting];
         [communityListTabelView.mj_header endRefreshing];
        if ([data objectForKey:@"data"] != nil)
        {
            [weakSelf getDataFromContentFile];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
            if ([[error objectForKey:@"status"] integerValue] == 210) {//没有添加任何集群
                promtView.hidden = NO;
                [singleton singleRelease];
                [weakSelf roleJudge];
                [weakSelf animationWithTabelViewHidden];
                [communityListTabelView reloadData];
            }
        }
       
    };  
}

-(void)getDataFromContentFile
{
    [communityListArray removeAllObjects];
    NSMutableDictionary * data = [OpertionPlist readDataFromPlist];
    NSArray * communityData = [data objectForKey:COMMUNITYINFOFORKEY];
    CommunityListInfo * listInfo = [[CommunityListInfo alloc]init];
    for (NSDictionary * dict in communityData) {
        CommunityListModel * model = [[CommunityListModel alloc]init];
        model.communityName = [dict objectForKey:@"communityname"];
        model.communityId = [dict objectForKey:@"communityid"];
        model.role = [dict objectForKey:@"role"];
        model.areaCodeString = [dict objectForKey:@"areaCode"];
        [communityListArray addObject:model];
        [listInfo deleteCommunityListInfo:[dict objectForKey:@"communityid"]];
        [listInfo insertCommunityListInfo:[dict objectForKey:@"communityid"] withCommunityName:[dict objectForKey:@"communityname"] withCommunityAreaCode:[dict objectForKey:@"communityid"]];
    }
    //没有集群到有集群
    if (singleton.communityId == nil || [singleton.communityId isEqualToString:@""]) {
        if (communityListArray.count > 0) {
            CommunityListModel * model = communityListArray[0];
            singleton.roleIndex = [model.role integerValue];
            singleton.communityId = model.communityId;
            singleton.communityName = model.communityName;
            singleton.currentAreaCodeString = model.areaCodeString;
            [[NSUserDefaults standardUserDefaults] setObject:model.communityId forKey:@"communityId"];
        }
    }
    //当前集群被删除
    BOOL flag = NO;
    for (CommunityListModel * model in communityListArray) {
        if ([model.communityId isEqualToString:singleton.communityId]) {
            singleton.roleIndex = [model.role integerValue];
            flag = YES;
        }
    }
    if (!flag && communityListArray.count > 0) {
        CommunityListModel * model = communityListArray[0];
        singleton.roleIndex = [model.role integerValue];
        singleton.communityId = model.communityId;
        singleton.communityName = model.communityName;
        singleton.currentAreaCodeString = model.areaCodeString;
         [[NSUserDefaults standardUserDefaults] setObject:model.communityId forKey:@"communityId"];
    }
    [communityListTabelView reloadData];
    [self roleJudge];
}

#pragma mark ----------- tableview的出场动画
-(void)animationWithTableViewShow
{
     backView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = communityListTabelView.frame;
        frame.origin.y = UI_SCREEN_HEIGHT - communityListTabelView.frame.size.height;
        communityListTabelView.frame = frame;
    } completion:^(BOOL finished) {
    }];
}

#pragma mark ----------- tableview的消失
-(void)animationWithTabelViewHidden
{
    [UIView animateWithDuration:0.5 animations:^{
        CGRect frame = communityListTabelView.frame;
        frame.origin.y = UI_SCREEN_HEIGHT;
        communityListTabelView.frame = frame;
    } completion:^(BOOL finished) {
         backView.hidden = YES;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
